import React, { Component } from 'react'
import Alert from '../../components/alert/alert'
import axios from 'axios'
import Context from '../../utils/context'

export default class user extends Component {
    static contextType = Context;
    state = {
        users: [],
        isShow: false,
        type: 1,
        item: null
    }
    componentDidMount() {
        axios.get('/user.json').then(({ data }) => {
            this.setState({ users: data })
        })

    }
    // static getDerivedStateFromProps(props){

    // }
    render() {
        let { users, isShow, type, item } = this.state
        return (
            <div className='user'>

                <button onClick={this.logout}>退出登录</button><br />
                <button onClick={this.add}>添加用户</button>
                <ul>
                    <li>编号</li>
                    <li>姓名</li>
                    <li>性别</li>
                    <li>电话</li>
                    <li>密码</li>
                    <li>操作</li>
                </ul>
                <div>
                    {
                        users.map((item,index) => {
                            return <ul key={item.id}>
                                <li>{index}</li>
                                <li>{item.name}</li>
                                <li>{item.age}</li>
                                <li>{item.sj}</li>
                                <li>{item.mi}</li>
                                <li>
                                    <button onClick={() => { this.set(item) }}>修改</button>
                                    <button onClick={() => { this.dis(item) }}>删除</button>
                                </li>
                            </ul>
                        })
                    }
                </div>

                {
                    isShow ? <Alert>{{ type, item, closeAlert: this.closeAlert ,setData:this.setData}}</Alert> : null
                }
            </div>
        )
    }
    add = () => {
        this.setState({ isShow: true })
        this.setState({ type: 1 })
    }
    set = (item) => {
        this.setState({ isShow: true })
        this.setState({ type: 2 })
        this.setState({ item })
    }
    dis = (item) => {
        this.setState({ isShow: true })
        this.setState({ type: 3 })
        this.setState({ item })
    }
    setData=(val)=>{
        this.setState({users:val})
    }
    closeAlert = () => {
        this.setState({ isShow: false })
    }
    logout = () => {
        sessionStorage.removeItem('token')
        this.setState({ name: null })
        this.props.history.push('/login')
    }
}
